<?php
namespace StarCloud\Library\Im;

use Framework\DiServices\HttpClient;

class TimRestApi
{
    protected $appId = '';
    protected $key = '';
    protected $identifier = 'administrator';
    protected $signApi = null;

    const API_URL_PREFIX = 'https://console.tim.qq.com/v4/';
    const ACCOUNT_IMPORT = 'im_open_login_svc/account_import';
    const ACCOUNT_CHECK = 'im_open_login_svc/account_check';
    const QUERY_ONLINE_STATUS = 'openim/query_online_status';

    public function __construct($appId, $key, $identifier)
    {
        $this->appId = $appId;
        $this->key = $key;
        $this->signApi = new TLSSigAPIv2($this->appId, $this->key);
        $this->identifier = $identifier;
        $this->httpClient = new HttpClient(8, 5);
    }

    public function genUserSig($userId)
    {
        return $this->signApi->genUserSig($userId);
    }
    private function buildUri($url)
    {
        return $url . '?' .http_build_query([
            'sdkappid' => $this->appId,
            'contenttype' => 'json',
            'identifier' => $this->identifier,
            'random' => time(),
            'usersig' => $this->signApi->genUserSig($this->identifier)
        ]);
    }

    public function account_import($userId, $nick, $faceUrl)
    {
        $body = [
            'UserID' => $userId,
            'Nick' => $nick,
            'FaceUrl' => $faceUrl,
        ];

        $response = $this->httpClient->sendPostRequest($this->buildUri(self::API_URL_PREFIX . self::ACCOUNT_IMPORT), $body);

        return $response->getBody()->getContents();
    }

    public function account_check(array $userIds)
    {
        $body['CheckItem'] = [];

        foreach ($userIds as $userId) {
            $body['CheckItem'][] = [
                'UserID' => $userId
            ];
        }

        $response = $this->httpClient->sendPostRequest($this->buildUri(self::API_URL_PREFIX . self::ACCOUNT_CHECK), $body);

        return $response->getBody()->getContents();
    }

    public function query_online_status($userIds, $isNeedDetail = false)
    {
        $body['To_Account'] = $userIds;

        $isNeedDetail && $body['IsNeedDetail'] = 1;

        $response = $this->httpClient->sendPostRequest($this->buildUri(self::API_URL_PREFIX . self::QUERY_ONLINE_STATUS), $body);

        return $response->getBody()->getContents();
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file=false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://")!==false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {
            if ($is_curlFile) {
                foreach ($param as $key => $val) {
                    if (substr($val, 0, 1) == '@') {
                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));
                    }
                }
            }
            $strPOST = $param;
        } else {
            $aPOST = [];
            foreach ($param as $key=>$val) {
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"])==200) {
            return $sContent;
        } else {
            return false;
        }
    }
}
